﻿using GenericRepositoryUnitOfWorkDemo.Domain.Abstracts.Entites;
using GenericRepositoryUnitOfWorkDemo.Domain.Abstracts.Repositories;
using Microsoft.EntityFrameworkCore;

namespace GenericRepositoryUnitOfWorkDemo.Infrastructure.Abstracts.Repositories;

public static class EfCoreRepositoryExtensions
{
    public static Task<DbContext> GetDbContextAsync<TEntity, TKey>(this IRepository<TEntity, TKey> repository)
        where TEntity : class, IEntity<TKey>
    {
        return repository.ToEfCoreRepositoryBase().GetDbContextAsync();
    }

    public static Task<DbSet<TEntity>> GetDbSetAsync<TDbContext, TEntity, TKey>(this IRepository<TEntity, TKey> repository)
        where TEntity : class, IEntity<TKey>
    {
        return repository.ToEfCoreRepositoryBase().GetDbSetAsync();
    }

    public static IEfCoreRepositoryBase<TEntity, TKey> ToEfCoreRepositoryBase<TEntity, TKey>(this IRepository<TEntity, TKey> repository)
        where TEntity : class, IEntity<TKey>
    {
        if (repository is IEfCoreRepositoryBase<TEntity, TKey> efCoreRepository)
        {
            return efCoreRepository;
        }

        throw new ArgumentException("Given repository does not implement " + typeof(IEfCoreRepositoryBase<TEntity, TKey>).AssemblyQualifiedName, nameof(repository));
    }
}
